<!--
 * @Author: your name
 * @Date: 2021-03-05 16:12:23
 * @LastEditTime: 2021-03-17 13:42:29
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \sende_nuxt\components\common\TryOn.vue
-->
<template>
  <div class="s12 flex tryAlert">
    <div class="tryAlert_left spacing">
      <ul class="glasses-list">
        <li
          class="glasses-item text_c ptb15 plr4 spacing mb10"
          :class="{ glassesActive: currentIndex === 0 }"
          @click="changeImgIndex(0)"
        >
          <img
            :src="require('~/assets/image/tryGlasses/1.png')"
            alt=""
            class="img"
          />
        </li>
        <li
          class="glasses-item text_c ptb15 plr4 spacing mb10"
          :class="{ glassesActive: currentIndex === 1 }"
          @click="changeImgIndex(1)"
        >
          <img
            :src="require('~/assets/image/tryGlasses/2.png')"
            alt=""
            class="img"
          />
        </li>
        <li
          class="glasses-item text_c ptb15 plr4 spacing mb10"
          :class="{ glassesActive: currentIndex === 2 }"
          @click="changeImgIndex(2)"
        >
          <img
            :src="require('~/assets/image/tryGlasses/3.png')"
            alt=""
            class="img"
          />
        </li>
        <li
          class="glasses-item text_c ptb15 plr4 spacing mb10"
          :class="{ glassesActive: currentIndex === 3 }"
          @click="changeImgIndex(3)"
        >
          <img
            :src="require('~/assets/image/tryGlasses/4.png')"
            alt=""
            class="img"
          />
        </li>
      </ul>
    </div>
    <div class="tryAlert_right spacing plr10">
      <div class="top relative h480">
        <div class="headbox s12 spacing mt15 relative">
          <img
            :src="curHeadImg"
            ref="headCanvas"
            id="headCanvas"
            class="head img"
            :style="{ transform: 'rotate(' + rotateIndex * 90 + 'deg)' }"
            alt=""
          />
          <img
            :src="curGlassesImg"
            class="absolute glassMove"
            id="glassesMove"
            ref="glassesMove"
            :style="[
              {
                transform:
                  'rotate(' + rotateNum + 'deg) scale(' + scaleNum + ')',
              },
            ]"
            @mousemove.stop="handleMouseMove($event)"
            @mousedown.prevent="handleMouseDown($event)"
            @mouseup.stop="handleMouseUp($event)"
            alt=""
          />
        </div>
        <div class="s12 absolute headbox_tool text_r spacing">
          <img
            :src="require('~/assets/image/rotate.png')"
            class="headbox_tool_img"
            alt=""
            @click="_rotate()"
          />
        </div>
      </div>
      <div class="toobar">
        <div class="try-scale">
          <img
            :src="require('~/assets/image/narrow_pc.png')"
            class="icon mr20"
            alt=""
            @click="shrink()"
          />
          <div class="try-swiper-box">
            <input
              type="range"
              ref="scaleNum"
              v-model="scaleNum"
              min="0"
              max="2"
              step="0.1"
              class="try-swiper-input"
            />
          </div>
          <img
            :src="require('~/assets/image/add_pc.png')"
            class="icon ml20"
            alt=""
            @click="amplify()"
          />
        </div>
        <div class="try-rotate">
          <img
            :src="require('~/assets/image/turn_left_pc.png')"
            class="icon mr20"
            alt=""
            @click="turnLeft()"
          />
          <div class="try-swiper-box">
            <input
              type="range"
              ref="rotateNum"
              v-model="rotateNum"
              min="0"
              max="360"
              step="1"
              class="try-swiper-input"
            />
          </div>
          <img
            :src="require('~/assets/image/turn_right_pc.png')"
            class="icon ml20"
            alt=""
            @click="turnRight()"
          />
        </div>
      </div>
      <div v-swiper:mySwiper="swiperOption" class="s12 mb20">
        <div class="swiper-wrapper">
          <div
            class="swiper-slide"
            v-for="(item, index) of swpierList"
            :key="'item' + index"
          >
            <img
              class="img"
              :src="item.banner_image"
              alt=""
              @click="changeHead(item.banner_image)"
            />
            <span :class="{ add: item.add }" @click="delHeadImg(index)"></span>
          </div>
        </div>
        <div class="swiper-button-next"></div>
        <div class="swiper-button-prev"></div>
      </div>
      <div class="flex tryAlert_btn">
          <div class="btn size18 text_c b cfff pointer relative">
            <img :src="require('~/assets/image/upload.png')" class="upload_img mr10" alt="">
            <input type="file" ref="headImg" class="absolute try_upload s12 h100" accept="image/*" @change="addHeadImg($event)">
            {{$t("Upload Your Photo")}}
          </div>
          <div class="btn size18 text_c b cfff pointer relative" @click="alertCamera()">
            <img :src="require('~/assets/image/camera.png')" class="camera_img mr10" alt="">
            {{$t("Use Your Webcam")}}   
          </div>
      </div>
    </div>

    <el-dialog
      title="在线真人试戴"
      :visible.sync="isShowCamera"
      width="900px"
      :modal-append-to-body="false"
    >
      <div class="webcam-box flex">
        <video width="600px" height="600px" id="video" class="mr20"></video>
        <canvas width="200px" height="200px" id="canvas" style="width:200px;height:200px;"></canvas>
      </div>
      <div class="flex">
        <el-button type="primary" id="start" @click="openCamera()">打开摄像头</el-button>
        <el-button type="primary" id="snap" @click="snap()">截取图像</el-button>
        <el-button type="primary" id="close" @click="close()">关闭摄像头</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Swiper from "~/components/common/Swiper";
import { compare } from "~/utils/Utils";
export default {
  data() {
    return {
      currentIndex: 0,
      glassIsDown: false, // 是否点击了眼镜框
      glassX: 0,
      glassY: 0,
      glassL: 0,
      glassT: 0,
      curGlassesImg: '', // 当前定位的眼镜框
      curHeadImg: '', // 当前需要定位的人物头像
      rotateIndex: 0,  // 旋转的索引
      scaleNum: 1, // 缩放值
      rotateNum: 0, // 旋转角度
      swiperOption: {
        slidesPerView: 6,
        observer: true,
        observeParents: true,
        spaceBetween: 5,
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
      },
      swpierList: [
        {
          banner_image: require("~/assets/image/tryHead/1.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/2.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/3.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/4.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/5.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/6.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/7.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/8.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/9.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/10.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/11.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/12.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/13.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/14.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/1.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/2.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/3.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/4.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/5.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/6.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/7.jpg"),
        }
      ],
      isShowCamera: false, // 是否显示摄像头弹框
      MediaStreamTrack: ''
    };
  },
  props: {
    list: {
      type: [Array, Object],
      default: () => [
        {
          banner_image: require("~/assets/image/tryHead/1.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/2.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/3.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/4.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/5.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/6.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/7.png"),
        },
        {
          banner_image: require("~/assets/image/tryHead/8.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/9.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/10.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/11.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/12.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/13.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryHead/14.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/1.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/2.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/3.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/4.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/5.png"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/6.jpg"),
        },
        {
          banner_image: require("~/assets/image/tryChildHead/7.jpg"),
        },
      ],
    },
    glassesList: {
        type: [Array, Object],
        default: () => [
        {
          id: 1,
          imgUrl: require('~/assets/image/tryGlasses/1.png')
        },
        {
          id: 2,
          imgUrl: require('~/assets/image/tryGlasses/2.png')
        },
        {
          id: 3,
          imgUrl: require('~/assets/image/tryGlasses/3.png')
        },
        {
          id: 4,
          imgUrl: require('~/assets/image/tryGlasses/4.png')
        }
      ]
    },
    initData: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    initData(newval, oldval) {
      if(newval) {
        this.showTry()
      } else {
        this.closeTry()
      }
    }
  },
  components: {
    Swiper
  },
  mounted () {
    if(this.initData) {
      if (localStorage.getItem("swpierList")) {
        this.swpierList = JSON.parse(localStorage.getItem("swpierList"))
      } else {
        localStorage.setItem("swpierList", JSON.stringify(this.swpierList))
      }
      this.curHeadImg = this.swpierList[0].banner_image
      this.curGlassesImg = this.glassesList[0].imgUrl
      this.showTry()
    }
  },
  methods: {
    /**
     *@param: 
     *@description:
     *@author: Mister Wang
     *@date: 2021-03-11 17:54:07
    */
    close () {
      this.MediaStreamTrack && this.MediaStreamTrack.stop();
    },
    /**
     *@param: 
     *@description: 截取摄像头
     *@author: Mister Wang
     *@date: 2021-03-11 17:44:47
    */
    snap () {
      const canvas = document.getElementById("canvas");
      const context = canvas.getContext('2d');
      const video = document.getElementById("video");
      context.drawImage(video, 0, 0, 200, 200);
    },
    /**
     *@param: 
     *@description:
     *@author: Mister Wang
     *@date: 2021-03-11 17:37:17
    */
    openCamera () {
      let self = this;
      const video = document.getElementById("video");
      console.log('object :>> ', navigator.mediaDevices);
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({
            video: true,
            audio: true
        }).then(function (stream) {
          console.log(stream);
          self.MediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[1];
            try {
              video.srcObject = stream;
            } catch(err) {
              video.src = window.webkitURL.createObjectURL(stream);
            }
          video.play();
        }).catch(function(err){
            console.log(err);
        });
      } else if (navigator.getMedia) {
        navigator.getMedia({
            video: true
        }).then(function (stream) {
            console.log(stream);
            self.MediaStreamTrack = stream.getTracks()[1];
            try {
              video.srcObject = stream;
            } catch(err) {
              video.src = window.webkitURL.createObjectURL(stream);
            }
            video.play();
        }).catch(function(err){
            console.log(err);
        });
      }
    },
    /**
     *@param: 
     *@description: 显示摄像头弹框
     *@author: Mister Wang
     *@date: 2021-03-11 17:07:26
    */
    alertCamera () {
      this.isShowCamera = true
      setTimeout(() => {
        this.openCamera()
      }, 500)
    },
    /**
     *@param: 
     *@description: 删除头像图片
     *@author: Mister Wang
     *@date: 2021-03-11 16:49:58
    */
    delHeadImg (index) {
      this.swpierList.splice(index, 1)
      this.changeHead(this.swpierList[0].banner_image)
      localStorage.setItem("swpierList", JSON.stringify(this.swpierList))
    },
    /**
     *@param:
     *@description: 初始化数据
     *@author: Mister Wang
     *@date: 2021-03-05 14:43:18
     */
    closeTry() {
      this.curGlassesImg = require("~/assets/image/tryGlasses/1.png");
      this.curHeadImg = require("~/assets/image/tryHead/1.png");
      this.rotateIndex = 0;
      this.scaleNum = 1;
      this.rotateNum = 0;
    },
    /**
     *@param:
     *@description: 修改试戴头像
     *@author: Mister Wang
     *@date: 2021-03-05 11:19:45
     */
    changeHead(img) {
      this.curHeadImg = img;
      this.initPosition(this.curHeadImg);
    },
    /**
     *@param:
     *@description: 眼镜框的右旋转
     *@author: Mister Wang
     *@date: 2021-03-05 10:11:07
     */
    turnRight(val) {
      if (!val) {
        this.rotateNum += 1;
      }
    },
    /**
     *@param:
     *@description: 眼镜框的左旋转
     *@author: Mister Wang
     *@date: 2021-03-05 10:08:50
     */
    turnLeft(val) {
      if (!val) {
        this.rotateNum -= 1;
      }
    },
    /**
     *@param:
     *@description: 眼镜框的放大
     *@author: Mister Wang
     *@date: 2021-03-05 10:03:51
     */
    amplify(val = "") {
      if (!val) {
        this.scaleNum += 0.1;
      }
    },
    /**
     *@param:
     *@description: 眼镜框的缩小
     *@author: Mister Wang
     *@date: 2021-03-05 10:01:00
     */
    shrink(val = "") {
      if (!val) {
        this.scaleNum -= 0.1;
      }
    },
    /**
     *@param:
     *@description:  人物图旋转
     *@author: Mister Wang
     *@date: 2021-03-04 11:20:52
     */
    _rotate() {
      if (this.rotateIndex < 4) {
        this.rotateIndex += 1;
      } else {
        this.rotateIndex = 0;
        this.rotateIndex += 1;
      }
    },
    /**
     *@param:
     *@description: 眼镜框定位
     *@author: Mister Wang
     *@date: 2021-03-04 11:04:37
     */
    glassPosition() {
      let glassDom = document.getElementById("glassesMove");
      // glassesobj:镜框图片;_widthDom:大图宽度
      var objects = new tracking.ObjectTracker(["eye"]);
      objects.setStepSize(1);
      // 跟踪器实例监听track事
      tracking.track("#headCanvas", objects);
      // 监听track事件
      objects.on("track", function (event) {
        if (event.data.length < 1) {
          // No objects were detected in this frame.
        } else if (event.data.length === 1) {
          var curWidth = 480;
          var options = event.data.sort(compare("total"));
          var glassesLeft =
              options[0].x > 243
                ? ((options[0].x / 2 + 0) / 480) * curWidth
                : ((options[0].x - 20) / 480) * curWidth,
            glassesWidth = (((options[0].width + 60) * 2) / 480) * curWidth,
            glassesTop = ((options[0].y - 10) / 480) * curWidth;
          glassDom.style.width = glassesWidth + "px";
          glassDom.style.left = glassesLeft + "px";
          glassDom.style.top = glassesTop + "px";
        } else if (event.data.length >= 2) {
          var curWidth = 480;
          var options = event.data.sort(compare("total"));
          var glassesLeft =
              options[options.length - 1].x < options[options.length - 2].x
                ? ((options[options.length - 1].x - 25) / 480) * curWidth
                : ((options[options.length - 2].x - 25) / 480) * curWidth,
            glassesWidth =
              options[options.length - 1].x < options[options.length - 2].x
                ? ((options[options.length - 2].width +
                    options[options.length - 2].x -
                    options[options.length - 1].x +
                    60) /
                    480) *
                  curWidth
                : ((options[options.length - 1].width +
                    options[options.length - 1].x -
                    options[options.length - 2].x +
                    60) /
                    480) *
                  curWidth,
            glassesTop =
              options[options.length - 1].y < options[options.length - 2].y
                ? ((options[options.length - 1].y - 5) / 480) * curWidth
                : ((options[options.length - 2].y - 5) / 480) * curWidth;

          glassDom.style.width = glassesWidth + "px";
          glassDom.style.left = glassesLeft + "px";
          glassDom.style.top = glassesTop + "px";
        }
        // 用来测试眼部识别框
        // event.data.forEach(function(rect) {
        //   self.plot(rect.x, rect.y, rect.width, rect.height);
        // });
      });
    },
    /**
     *@param:
     *@description: 绘制眼部识别框
     *@author: Mister Wang
     *@date: 2021-03-04 11:18:33
     */
    plot(x, y, w, h) {
      let headCanvas = document.getElementById("headCanvas");
      var rect = document.createElement("div");
      document.querySelector(".headbox").appendChild(rect);
      rect.classList.add("rect");
      rect.style.width = w + "px";
      rect.style.height = h + "px";
      rect.style.left = headCanvas.offsetLeft + x + "px";
      rect.style.top = headCanvas.offsetTop + y + "px";
      rect.style.position = "absolute";
      rect.style.border = "2px solid #a64ceb";
    },
    // 眼镜拖拽 鼠标移动
    handleMouseMove(event) {
      if (this.glassIsDown == false) {
        return;
      }
      // 眼镜 dom
      let glassDom = document.getElementById("glassesMove");
      let nx = event.clientX;
      let ny = event.clientY;
      // 计算移动后的左偏移量和顶部的偏移量
      let nl = nx - (this.glassX - this.glassL);
      let nt = ny - (this.glassY - this.glassT);

      // 设置样式
      glassDom.style.left = nl + "px";
      glassDom.style.top = nt + "px";
      console.log("nx :>> ", nx);
      console.log("ny :>> ", ny);
    },
    // 眼镜拖拽 鼠标按下事件
    handleMouseDown(e) {
      e.preventDefault();
      console.log("clientX :>> ", e.clientX);
      console.log("clientY :>> ", e.clientY);
      // 眼镜 dom
      let glassDom = document.getElementById("glassesMove");
      //获取x坐标和y坐标
      this.glassX = e.clientX;
      this.glassY = e.clientY;
      //获取左部和顶部的偏移量
      this.glassL = glassDom.offsetLeft;
      this.glassT = glassDom.offsetTop;
      //开关打开
      this.glassIsDown = true;
      //设置样式
      glassDom.style.cursor = "move";
    },
    // 眼镜拖拽 鼠标抬起事件
    handleMouseUp(e) {
      // 眼镜 dom
      let glassDom = document.getElementById("glassesMove");
      // 开关关闭
      this.glassIsDown = false;
      // 设置样式
      glassDom.style.cursor = "default";
    },
    /**
     *@param:
     *@description: 加载头像初始化定位
     *@author: Mister Wang
     *@date: 2021-03-05 11:36:31
     */
    initPosition(img) {
      let self = this;
      var img = new Image();
      img.src = require("~/assets/image/tryHead/1.png");
      img.onload = function () {
        self.glassPosition();
      };
    },
    /**
     *@param:
     *@description: 修改头像图片
     *@author: Mister Wang
     *@date: 2021-03-04 09:40:10
     */
    changeImgIndex(index) {
      this.currentIndex = index;
      this.curGlassesImg = this.glassesList[index].imgUrl;
      this.initPosition(this.curGlassesImg);
    },
    /**
     *@param:
     *@description: 显示试戴弹窗
     *@author: Mister Wang
     *@date: 2021-03-04 09:28:03
     */
    showTry() {
      let self = this;
      var img = new Image();
      img.src = require("~/assets/image/tryHead/1.png");
      img.onload = function () {
        self.glassPosition();
      };
    },
    /**
     *@param: 
     *@description: 添加用户上传的图片
     *@author: Mister Wang
     *@date: 2021-03-05 17:34:14
    */
    addHeadImg (event) {
      let self = this;
      let obj = {};
      let ext = event.target.value.substring(event.target.value.lastIndexOf(".")+1).toLowerCase();
      if (/(png|jpg|jpeg|gif)/.test(ext)) {
        let file = this.$refs.headImg.files[0]
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          self.$set(obj, 'banner_image', this.result)
          self.$set(obj, 'add', true)
          self.swpierList.unshift(obj)
          self.changeHead(obj.banner_image)
          localStorage.setItem("swpierList", JSON.stringify(self.swpierList))
        }
      } else {
        this.$message({
          message: '请上传文件后缀为.(png、jpg、jpeg、gif)的图片',
          type: 'warning'
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~/assets/scss/index.scss";
.glasses-list {
  width: 240px;
  height: 480px;
  overflow-y: auto;
}
.glasses-item {
  width: 220px;
  height: 120px;
  border: 1px solid transparent;
}
.glassesActive {
  border-color: $ceb;
}
.tryAlert_right {
  width: 500px;
}
.glassMove {
  width: 40%;
  left: calc(50% - 125px);
  top: 30%;
}
.headbox_tool {
  left: 0;
  bottom: 0;
  height: 90px;
}
.headbox_tool_img {
  width: 70px;
  height: 70px;
}
.tryAlert_btn,
.toobar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
.btn,
.try-rotate,
.try-scale {
  display: flex;
  justify-content: center;
  align-items: center;
}
.camera_img,
.upload_img,
.icon {
  width: 20px;
  height: 20px;
}
.btn {
    width: 48%;
    height: 50px;
    background-color: #05a6f0;
    border-radius: 6px;
}
.try_upload {
    left: 0;
    top: 0;
    opacity: 0;
}
.h480 {
  height: 480px;
}
.add {
  position: absolute;
  right: 0;
  top: 0;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 1px solid #333;
}
.add::before,
.add::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 100%;
  height: 1px;
  background: #333;
}
.add::after {
  transform: rotate(45deg)
}
.add::before {
  transform: rotate(-45deg)
}
.webcam-box {
  justify-content: space-around;
}
</style>
<style>
.tryDialog .el-dialog__header {
  padding: 0;
}
.tryDialog .el-dialog__headerbtn {
  top: 10px;
  right: 10px;
}
.tryAlert_right .swiper-button-next { 
  height: 100%;
  top: 0;
  margin-top: 0;
  right: 0;
  width: 20px;
  background-size: 50% 50%;
  background-color: rgba(255,255,255,.8);
}
.tryAlert_right .swiper-button-prev {
  height: 100%;
  top: 0;
  margin-top: 0;
  left: 0;
  width: 20px;
  background-size: 50% 50%;
  background-color: rgba(255,255,255,.5);
}
</style>